document.addEventListener('DOMContentLoaded', function() {
    // 初始化Feather图标
    feather.replace();
    
    // 获取DOM元素
    const qrContent = document.getElementById('qrContent');
    const qrSize = document.getElementById('qrSize');
    const qrSizeValue = document.getElementById('qrSizeValue');
    const qrMargin = document.getElementById('qrMargin');
    const qrMarginValue = document.getElementById('qrMarginValue');
    const dotStyleSquare = document.getElementById('dotStyleSquare');
    const dotStyleRound = document.getElementById('dotStyleRound');
    
    const bgColor = document.getElementById('bgColor');
    const bgColorText = document.getElementById('bgColorText');
    const fgColor = document.getElementById('fgColor');
    const fgColorText = document.getElementById('fgColorText');
    const eyeColor = document.getElementById('eyeColor');
    const eyeColorText = document.getElementById('eyeColorText');
    const eyeRadius = document.getElementById('eyeRadius');
    const eyeRadiusValue = document.getElementById('eyeRadiusValue');
    
    const uploadLogo = document.getElementById('uploadLogo');
    const logoInput = document.getElementById('logoInput');
    const removeLogo = document.getElementById('removeLogo');
    const logoSettings = document.getElementById('logoSettings');
    const logoPreview = document.getElementById('logoPreview').querySelector('img');
    const logoWidth = document.getElementById('logoWidth');
    const logoWidthValue = document.getElementById('logoWidthValue');
    const logoHeight = document.getElementById('logoHeight');
    const logoHeightValue = document.getElementById('logoHeightValue');
    const logoOpacity = document.getElementById('logoOpacity');
    const logoOpacityValue = document.getElementById('logoOpacityValue');
    const removeQrBehindLogo = document.getElementById('removeQrBehindLogo');
    
    const qrCodePreview = document.getElementById('qrCodePreview');
    const copyQrCode = document.getElementById('copyQrCode');
    const downloadQrCode = document.getElementById('downloadQrCode');
    const resetSettings = document.getElementById('resetSettings');
    
    // 二维码配置
    let qrConfig = {
        content: 'https://example.com',
        size: 200,
        margin: 10,
        dotStyle: 'square', // 'square' 或 'round'
        bgColor: '#FFFFFF',
        fgColor: '#000000',
        eyeColor: '#000000',
        eyeRadius: 0,
        logo: null,
        logoWidth: 60,
        logoHeight: 42,
        logoOpacity: 100,
        removeQrBehindLogo: true
    };
    
    // 初始化二维码
    generateQRCode();
    
    // 事件监听器 - 基本设置
    qrContent.addEventListener('input', function() {
        qrConfig.content = this.value || 'https://example.com';
        generateQRCode();
    });
    
    qrSize.addEventListener('input', function() {
        qrConfig.size = parseInt(this.value);
        qrSizeValue.textContent = this.value;
        generateQRCode();
    });
    
    qrMargin.addEventListener('input', function() {
        qrConfig.margin = parseInt(this.value);
        qrMarginValue.textContent = this.value;
        generateQRCode();
    });
    
    dotStyleSquare.addEventListener('click', function() {
        dotStyleSquare.classList.add('btn-primary');
        dotStyleSquare.classList.remove('btn-outline-primary');
        dotStyleRound.classList.add('btn-outline-primary');
        dotStyleRound.classList.remove('btn-primary');
        qrConfig.dotStyle = 'square';
        generateQRCode();
    });
    
    dotStyleRound.addEventListener('click', function() {
        dotStyleRound.classList.add('btn-primary');
        dotStyleRound.classList.remove('btn-outline-primary');
        dotStyleSquare.classList.add('btn-outline-primary');
        dotStyleSquare.classList.remove('btn-primary');
        qrConfig.dotStyle = 'round';
        generateQRCode();
    });
    
    // 事件监听器 - 颜色设置
    bgColor.addEventListener('input', function() {
        qrConfig.bgColor = this.value;
        bgColorText.value = this.value;
        generateQRCode();
    });
    
    bgColorText.addEventListener('input', function() {
        if (isValidHexColor(this.value)) {
            qrConfig.bgColor = this.value;
            bgColor.value = this.value;
            generateQRCode();
        }
    });
    
    fgColor.addEventListener('input', function() {
        qrConfig.fgColor = this.value;
        fgColorText.value = this.value;
        generateQRCode();
    });
    
    fgColorText.addEventListener('input', function() {
        if (isValidHexColor(this.value)) {
            qrConfig.fgColor = this.value;
            fgColor.value = this.value;
            generateQRCode();
        }
    });
    
    eyeColor.addEventListener('input', function() {
        qrConfig.eyeColor = this.value;
        eyeColorText.value = this.value;
        generateQRCode();
    });
    
    eyeColorText.addEventListener('input', function() {
        if (isValidHexColor(this.value)) {
            qrConfig.eyeColor = this.value;
            eyeColor.value = this.value;
            generateQRCode();
        }
    });
    
    eyeRadius.addEventListener('input', function() {
        qrConfig.eyeRadius = parseInt(this.value);
        eyeRadiusValue.textContent = this.value + '%';
        generateQRCode();
    });
    
    // 预设颜色按钮
    document.querySelectorAll('.preset-color').forEach(button => {
        button.addEventListener('click', function() {
            const bg = this.getAttribute('data-bg');
            const fg = this.getAttribute('data-fg');
            const eye = this.getAttribute('data-eye');
            
            qrConfig.bgColor = bg;
            qrConfig.fgColor = fg;
            qrConfig.eyeColor = eye;
            
            bgColor.value = bg;
            bgColorText.value = bg;
            fgColor.value = fg;
            fgColorText.value = fg;
            eyeColor.value = eye;
            eyeColorText.value = eye;
            
            generateQRCode();
        });
    });
    
    // 事件监听器 - Logo设置
    uploadLogo.addEventListener('click', function() {
        logoInput.click();
    });
    
    logoInput.addEventListener('change', function(e) {
        if (e.target.files && e.target.files[0]) {
            const reader = new FileReader();
            reader.onload = function(event) {
                qrConfig.logo = event.target.result;
                logoPreview.src = event.target.result;
                logoSettings.style.display = 'block';
                removeLogo.style.display = 'block';
                generateQRCode();
            };
            reader.readAsDataURL(e.target.files[0]);
        }
    });
    
    removeLogo.addEventListener('click', function() {
        qrConfig.logo = null;
        logoPreview.src = '';
        logoSettings.style.display = 'none';
        removeLogo.style.display = 'none';
        logoInput.value = '';
        generateQRCode();
    });
    
    logoWidth.addEventListener('input', function() {
        qrConfig.logoWidth = parseInt(this.value);
        logoWidthValue.textContent = this.value;
        generateQRCode();
    });
    
    logoHeight.addEventListener('input', function() {
        qrConfig.logoHeight = parseInt(this.value);
        logoHeightValue.textContent = this.value;
        generateQRCode();
    });
    
    logoOpacity.addEventListener('input', function() {
        qrConfig.logoOpacity = parseInt(this.value);
        logoOpacityValue.textContent = this.value + '%';
        generateQRCode();
    });
    
    removeQrBehindLogo.addEventListener('change', function() {
        qrConfig.removeQrBehindLogo = this.checked;
        generateQRCode();
    });
    
    // 复制、下载和重置按钮
    copyQrCode.addEventListener('click', function() {
        htmlToImage.toPng(qrCodePreview.querySelector('canvas'))
            .then(function(dataUrl) {
                copyImageToClipboard(dataUrl);
                showToast('二维码已复制到剪贴板');
            })
            .catch(function(error) {
                console.error('复制二维码失败:', error);
                showToast('复制失败，请重试', 'error');
            });
    });
    
    downloadQrCode.addEventListener('click', function() {
        htmlToImage.toPng(qrCodePreview.querySelector('canvas'))
            .then(function(dataUrl) {
                const link = document.createElement('a');
                link.download = 'qrcode.png';
                link.href = dataUrl;
                link.click();
            })
            .catch(function(error) {
                console.error('下载二维码失败:', error);
                showToast('下载失败，请重试', 'error');
            });
    });
    
    resetSettings.addEventListener('click', function() {
        // 重置所有设置
        qrConfig = {
            content: 'https://example.com',
            size: 200,
            margin: 10,
            dotStyle: 'square',
            bgColor: '#FFFFFF',
            fgColor: '#000000',
            eyeColor: '#000000',
            eyeRadius: 0,
            logo: null,
            logoWidth: 60,
            logoHeight: 42,
            logoOpacity: 100,
            removeQrBehindLogo: true
        };
        
        // 更新UI
        qrContent.value = qrConfig.content;
        qrSize.value = qrConfig.size;
        qrSizeValue.textContent = qrConfig.size;
        qrMargin.value = qrConfig.margin;
        qrMarginValue.textContent = qrConfig.margin;
        
        dotStyleSquare.classList.add('btn-primary');
        dotStyleSquare.classList.remove('btn-outline-primary');
        dotStyleRound.classList.add('btn-outline-primary');
        dotStyleRound.classList.remove('btn-primary');
        
        bgColor.value = qrConfig.bgColor;
        bgColorText.value = qrConfig.bgColor;
        fgColor.value = qrConfig.fgColor;
        fgColorText.value = qrConfig.fgColor;
        eyeColor.value = qrConfig.eyeColor;
        eyeColorText.value = qrConfig.eyeColor;
        eyeRadius.value = qrConfig.eyeRadius;
        eyeRadiusValue.textContent = qrConfig.eyeRadius + '%';
        
        logoSettings.style.display = 'none';
        removeLogo.style.display = 'none';
        logoInput.value = '';
        logoWidth.value = qrConfig.logoWidth;
        logoWidthValue.textContent = qrConfig.logoWidth;
        logoHeight.value = qrConfig.logoHeight;
        logoHeightValue.textContent = qrConfig.logoHeight;
        logoOpacity.value = qrConfig.logoOpacity;
        logoOpacityValue.textContent = qrConfig.logoOpacity + '%';
        removeQrBehindLogo.checked = qrConfig.removeQrBehindLogo;
        
        generateQRCode();
        showToast('设置已重置');
    });
    
    // 生成二维码函数
    function generateQRCode() {
        // 清空预览区域
        qrCodePreview.innerHTML = '';
        
        // 创建QR码
        const qr = qrcode(0, 'L');
        qr.addData(qrConfig.content);
        qr.make();
        
        // 创建Canvas元素
        const canvas = document.createElement('canvas');
        const size = qrConfig.size;
        const margin = qrConfig.margin;
        const totalSize = size + 2 * margin;
        canvas.width = totalSize;
        canvas.height = totalSize;
        
        const ctx = canvas.getContext('2d');
        
        // 绘制背景
        ctx.fillStyle = qrConfig.bgColor;
        ctx.fillRect(0, 0, totalSize, totalSize);
        
        // 获取QR码模块数据
        const modules = qr.getModuleCount();
        const moduleSize = size / modules;
        
        // 绘制QR码
        for (let row = 0; row < modules; row++) {
            for (let col = 0; col < modules; col++) {
                // 检查是否是定位点（眼睛）
                const isEye = (
                    // 左上角
                    (row < 7 && col < 7) ||
                    // 右上角
                    (row < 7 && col >= modules - 7) ||
                    // 左下角
                    (row >= modules - 7 && col < 7)
                );
                
                // 如果是定位点，使用眼睛颜色
                if (isEye) {
                    if (!qr.isDark(row, col)) continue;
                    
                    ctx.fillStyle = qrConfig.eyeColor;
                    
                    // 计算模块位置
                    const x = margin + col * moduleSize;
                    const y = margin + row * moduleSize;
                    
                    // 绘制圆角矩形或圆形
                    if (qrConfig.eyeRadius > 0) {
                        const radius = (moduleSize * qrConfig.eyeRadius) / 100;
                        roundRect(ctx, x, y, moduleSize, moduleSize, radius);
                    } else {
                        ctx.fillRect(x, y, moduleSize, moduleSize);
                    }
                }
                // 普通数据点
                else if (qr.isDark(row, col)) {
                    ctx.fillStyle = qrConfig.fgColor;
                    
                    // 计算模块位置
                    const x = margin + col * moduleSize;
                    const y = margin + row * moduleSize;
                    
                    // 根据点样式绘制
                    if (qrConfig.dotStyle === 'round') {
                        ctx.beginPath();
                        ctx.arc(x + moduleSize / 2, y + moduleSize / 2, moduleSize / 2, 0, Math.PI * 2);
                        ctx.fill();
                    } else {
                        ctx.fillRect(x, y, moduleSize, moduleSize);
                    }
                }
            }
        }
        
        // 如果有Logo，添加到中心
        if (qrConfig.logo) {
            const logoImg = new Image();
            logoImg.onload = function() {
                // 计算Logo位置
                const logoWidth = qrConfig.logoWidth;
                const logoHeight = qrConfig.logoHeight;
                const logoX = (totalSize - logoWidth) / 2;
                const logoY = (totalSize - logoHeight) / 2;
                
                // 如果需要移除Logo后方的二维码
                if (qrConfig.removeQrBehindLogo) {
                    ctx.fillStyle = qrConfig.bgColor;
                    ctx.fillRect(logoX, logoY, logoWidth, logoHeight);
                }
                
                // 设置Logo透明度
                ctx.globalAlpha = qrConfig.logoOpacity / 100;
                
                // 绘制Logo
                ctx.drawImage(logoImg, logoX, logoY, logoWidth, logoHeight);
                
                // 重置透明度
                ctx.globalAlpha = 1.0;
            };
            logoImg.src = qrConfig.logo;
        }
        
        // 添加到预览区域
        qrCodePreview.appendChild(canvas);
    }
    
    // 辅助函数 - 绘制圆角矩形
    function roundRect(ctx, x, y, width, height, radius) {
        ctx.beginPath();
        ctx.moveTo(x + radius, y);
        ctx.lineTo(x + width - radius, y);
        ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
        ctx.lineTo(x + width, y + height - radius);
        ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
        ctx.lineTo(x + radius, y + height);
        ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
        ctx.lineTo(x, y + radius);
        ctx.quadraticCurveTo(x, y, x + radius, y);
        ctx.closePath();
        ctx.fill();
    }
    
    // 辅助函数 - 验证十六进制颜色
    function isValidHexColor(color) {
        return /^#([0-9A-F]{3}){1,2}$/i.test(color);
    }
    
    // 辅助函数 - 复制图片到剪贴板
    async function copyImageToClipboard(dataUrl) {
        try {
            const blob = await fetch(dataUrl).then(r => r.blob());
            await navigator.clipboard.write([
                new ClipboardItem({
                    [blob.type]: blob
                })
            ]);
            return true;
        } catch (error) {
            console.error('复制到剪贴板失败:', error);
            return false;
        }
    }
    
    // 辅助函数 - 显示提示消息
    function showToast(message, type = 'success') {
        // 创建toast元素
        const toast = document.createElement('div');
        toast.className = `toast ${type === 'error' ? 'toast-error' : 'toast-success'}`;
        toast.textContent = message;
        document.body.appendChild(toast);
        
        // 显示动画
        setTimeout(() => {
            toast.classList.add('show');
        }, 10);
        
        // 3秒后移除
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 300);
        }, 3000);
    }
});